package top.majuan.springboot3.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import top.majuan.springboot3.service.RedisService;
import top.majuan.springboot3.util.JsonUtils;

import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
@Slf4j
public class RedisServiceImpl implements RedisService {
    public final RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean has(String key) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }

    @Override
    public <T> void save(String key, T t) {
        String  value = JsonUtils.stringify(t);
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        ops.set(key, value);
    }

    @Override
    public <T> void save(String key, T t, int timeout) {
        String value = JsonUtils.stringify(t);
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        ops.set(key, value, timeout, TimeUnit.SECONDS);
    }

    @Override
    public <T> void update(String key, T t) {
        if (!has(key)) {
            return;
        }
        // 获取过期时间
        Long timeout = redisTemplate.getExpire(key);
        if(timeout == null || timeout <= 0) {
            return;
        }
        save(key, t, timeout.intValue());
    }
    @Override
    public <T> T  load(String key, Class<T> clazz) {
        if (!has(key)) {
            return null;
        }
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String value = ops.get(key);
        return JsonUtils.parse(value, clazz);
    }


    @Override
    public void delete(String key) {
        redisTemplate.delete(key);
    }
}
